package com.moshang.blog.controller.back.system;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.core.constant.Constants;
import com.moshang.blog.core.constant.CurrentUser;
import com.moshang.blog.entity.SysRole;
import com.moshang.blog.entity.SysUser;
import com.moshang.blog.entity.SysUserRole;
import com.moshang.blog.core.constant.MySysUser;
import com.moshang.blog.entity.vo.ShowMenu;
import com.moshang.blog.service.SysMenuService;
import com.moshang.blog.service.SysRoleService;
import com.moshang.blog.service.SysUserRoleService;
import com.moshang.blog.core.utils.*;
import com.moshang.blog.service.SysUsersService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author moshang
 * @email 597575122@qq.com
 * @date 2018-09-21 14:45:09
 */
@Controller
@RequestMapping("/back/system/sysUser")
public class SysUsersController {
    @Autowired
    private SysUsersService sysUsersService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @GetMapping("list")
    @SystemLog("跳转系统用户列表页面")
    public String list(){
        return "back/system/user/allUsers";
    }

    @RequiresPermissions("sys:user:list")
    @GetMapping("findList")
    @ResponseBody
    public PageUtil<SysUser> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                  @RequestParam(value = "limit",defaultValue = "10")Integer limit, ServletRequest request){
        Map<String,Object> map = WebUtils.getParametersStartingWith(request, "s_");
        PageUtil<SysUser> pageUtils = new PageUtil<>();
        QueryWrapper<SysUser> entity = new QueryWrapper<SysUser>();
        if(!map.isEmpty()){
            String userName = (String) map.get("userName");
            String roleName = (String) map.get("roleName");
            String age = (String) map.get("age");
            if(StringUtils.isNotBlank(userName)) {
                entity.eq("user_name", userName);
            }
            if(StringUtils.isNotBlank(roleName)) {
                entity.eq("role_name", roleName);
            }
            if(StringUtils.isNotBlank(age)) {
                entity.eq("age", age);
            }
        }
        IPage<SysUser> tablePage = sysUsersService.page(new Page<>(page,limit), entity);
        pageUtils.setCount((int) tablePage.getTotal());
        pageUtils.setData(tablePage.getRecords());
        return pageUtils;
    }


    /***
     * 获得用户所拥有的菜单列表
     * @return
     */
    @GetMapping("getUserMenu")
    @ResponseBody
    public List<ShowMenu> getUserMenu(HttpServletRequest request){
        CurrentUser currentUser = (CurrentUser) request.getSession().getAttribute("currentUser");
        List<ShowMenu> list = sysMenuService.getShowMenuByUserId(currentUser.getId());
        return list;
    }
    @GetMapping("userInfo")
    public String toEditMyInfo(Model model)  {
        Integer userId = MySysUser.id();
        SysUser user = sysUsersService.findUserById(userId);
        if (StringUtils.isBlank(user.getImage())){
            user.setImage(Constants.DEFAULT_IMAGE);
        }
        model.addAttribute("userInfo",user);
        model.addAttribute("userRole",user.getRoleLists());
        return "back/system/user/userInfo";
    }

    @PostMapping("saveUserInfo")
    @SystemLog("系统用户个人信息修改")
    @ResponseBody
    @ApiOperation(value = "/saveUserInfo", httpMethod = "POST", notes = "个人资料修改")
    public RestResponse saveUserInfo(SysUser user){
        if(user.getId() == 0 || user.getId() == null){
            return RestResponse.failure("用户ID不能为空");
        }
        if(StringUtils.isBlank(user.getUserName())){
            return RestResponse.failure("登录名不能为空");
        }
        SysUser oldUser = sysUsersService.findUserById(user.getId());
        if(StringUtils.isNotBlank(user.getEmail())){
            if(!user.getEmail().equals(oldUser.getEmail())){
                if(sysUsersService.userCount(user.getEmail())>0){
                    return RestResponse.failure("该邮箱已被使用");
                }
            }
        }

        user.setRoleLists(oldUser.getRoleLists());
        sysUsersService.updateUser(user);
        return RestResponse.success();
    }
    @GetMapping("changePassword")
    public String changePassword(Model model){
        SysUser user = sysUsersService.findUserById(MySysUser.id());
        if (StringUtils.isBlank(user.getImage())){
            user.setImage(Constants.DEFAULT_IMAGE);
        }
        model.addAttribute("user",user);
        return "back/system/user/changePwd";
    }
    @RequiresPermissions("sys:user:changePassword")
    @PostMapping("changePassword")
    @SystemLog("用户修改密码")
    @ResponseBody
    @ApiOperation(value = "/changePassword", httpMethod = "POST", notes = "修改用户密码")
    public RestResponse changePassword(@RequestParam(value = "oldPwd",required = false)String oldPwd,
                                       @RequestParam(value = "newPwd",required = false)String newPwd,
                                       @RequestParam(value = "confirmPwd",required = false)String confirmPwd){
        if(StringUtils.isBlank(oldPwd)){
            return RestResponse.failure("旧密码不能为空");
        }
        if(StringUtils.isBlank(newPwd)){
            return RestResponse.failure("新密码不能为空");
        }
        if(StringUtils.isBlank(confirmPwd)){
            return RestResponse.failure("确认密码不能为空");
        }
        if(!confirmPwd.equals(newPwd)){
            return RestResponse.failure("确认密码与新密码不一致");
        }
        SysUser user = sysUsersService.findUserById(MySysUser.id());

        //旧密码不能为空
        String pw = ToolUtil.entryptPassword(oldPwd,user.getSalt()).split(",")[0];
        if(!user.getPassword().equals(pw)){
            return RestResponse.failure("旧密码错误");
        }
        user.setPassword(newPwd);
        ToolUtil.entryptPassword(user);
        sysUsersService.updateUser(user);
        return RestResponse.success();
    }

    @PostMapping("updateUserState")
    @SystemLog("修改用户状态")
    @ResponseBody
    @ApiOperation(value = "/updateUserState", httpMethod = "POST", notes = "修改用户状态")
    public  RestResponse updateUserState(@RequestParam("id") Integer id,@RequestParam("locked") Integer locked){
        if(id==null){
            return RestResponse.failure("id不能为空");
        }
        SysUser user = sysUsersService.findUserById(id);
        user.setLocked(locked);
        user.setUpdateTime(new Date());
        user.setUpdateBy(MySysUser.id());
        user.setUpdateName(MySysUser.userName());
        sysUsersService.updateById(user);
        if (locked==1){
            return RestResponse.success("账户被锁定！");
        }else {
            return RestResponse.success("您的账户已被解锁！");

        }
    }

    /**
     * 进入添加用户页面
     * @param model
     * @return
     */
    @GetMapping("addUI")
    public String add(Model model){
        List<SysRole> roleList = roleService.selectAll();
        model.addAttribute("roleList",roleList);
        return "back/system/user/addUser";
    }

    /**
     * 添加用户操作
     * @param user
     * @return
     */
    @RequiresPermissions("sys:user:add")
    @PostMapping("add")
    @ResponseBody
    @SystemLog("保存新增系统用户数据")
    @ApiOperation(value = "/add", httpMethod = "POST", notes = "添加用户")
    public RestResponse add(SysUser user,@RequestParam(value = "roles[]",required = false) Integer[] roles){
        if(StringUtils.isBlank(user.getUserName())){
            return RestResponse.failure("登录名不能为空");
        }
        if(roles == null || roles.length == 0){
            return  RestResponse.failure("用户角色至少选择一个");
        }
        if(sysUsersService.userCount(user.getUserName())>0){
            return RestResponse.failure("登录名称已经存在");
        }
        if(StringUtils.isNotBlank(user.getEmail())){
            if(sysUsersService.userCount(user.getEmail())>0){
                return RestResponse.failure("该邮箱已被使用");
            }
        }
        if(StringUtils.isNoneBlank(user.getPhone())){
            if(sysUsersService.userCount(user.getPhone())>0){
                return RestResponse.failure("该手机号已被绑定");
            }
        }
        user.setPassword(Constants.DEFAULT_PASSWORD);
        sysUsersService.saveUser(user,roles);
        if(user.getId() == null || user.getId() == 0){
            return RestResponse.failure("保存用户信息出错");
        }
        return RestResponse.success();
    }

    /**
     * 进入修改用户页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("editUI")
    public String editUI(Integer id,Model model){
        SysUser user = sysUsersService.findUserById(id);
        List<Integer> roleIdList = new ArrayList<>();
        if(user != null) {
            List<SysUserRole> list = sysUserRoleService.findByUserId(user.getId());
            if (list != null && list.size() > 0) {
                for (SysUserRole r : list) {
                    roleIdList.add(r.getRoleId());
                }
            }
        }
        List<SysRole> roleList =roleService.selectAll();
        if (StringUtils.isBlank(user.getImage())){
            user.setImage(Constants.DEFAULT_IMAGE);
        }
        model.addAttribute("user",user);
        model.addAttribute("roleIdList",roleIdList);
        model.addAttribute("roleList",roleList);
        return "back/system/user/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @PostMapping("edit")
    @ResponseBody
    @SystemLog("保存系统用户编辑数据")
    @ApiOperation(value = "/edit", httpMethod = "POST", notes = "修改用户")
    public RestResponse edit(SysUser user,@RequestParam(value = "roles[]",required = false) Integer[] roles){
        if(user.getId() == 0 || user.getId() == null){
            return RestResponse.failure("用户ID不能为空");
        }
        if(StringUtils.isBlank(user.getUserName())){
            return RestResponse.failure("登录名不能为空");
        }
        if(roles== null || roles.length == 0){
            return  RestResponse.failure("用户角色至少选择一个");
        }
        SysUser oldUser = sysUsersService.findUserById(user.getId());
        if(StringUtils.isNotBlank(user.getEmail())){
            if(!user.getEmail().equals(oldUser.getEmail())){
                if(sysUsersService.userCount(user.getEmail())>0){
                    return RestResponse.failure("该邮箱已被使用");
                }
            }
        }
        if(StringUtils.isNotBlank(user.getUserName())){
            if(!user.getUserName().equals(oldUser.getUserName())) {
                if (sysUsersService.userCount(user.getUserName()) > 0) {
                    return RestResponse.failure("该登录名已存在");
                }
            }
        }
        if(StringUtils.isNotBlank(user.getPhone())){
            if(!user.getPhone().equals(oldUser.getPhone())) {
                if (sysUsersService.userCount(user.getPhone()) > 0) {
                    return RestResponse.failure("该手机号已经被绑定");
                }
            }
        }
        user.setUpdateName(MySysUser.userName());
        user.setUpdateBy(MySysUser.id());
        user.setUpdateTime(new Date());
        sysUsersService.updateUser(user,roles);

        return RestResponse.success("修改用户成功！");
    }

    @RequiresPermissions("sys:user:delete")
    @PostMapping("delete")
    @ResponseBody
    @SystemLog("删除系统用户数据(单个)")
    @ApiOperation(value = "/delete", httpMethod = "POST", notes = "删除用户")
    public RestResponse delete(@RequestParam(value = "id",required = false)Integer id){
        if(id == null || id == 0 || id == 1){
            return RestResponse.failure("参数错误");
        }
        SysUser user = sysUsersService.findUserById(id);
        if(user == null){
            return RestResponse.failure("用户不存在");
        }
        sysUsersService.deleteUser(user);
        return RestResponse.success();
    }

    @RequiresPermissions("sys:user:delete")
    @PostMapping("batchDelete")
    @ResponseBody
    @SystemLog("删除系统用户数据(多个)")
    @ApiOperation(value = "/batchDelete", httpMethod = "POST", notes = "批量删除用户")
    public RestResponse batchDelete(@RequestBody List<SysUser> users){
        if(users == null || users.size()==0){
            return RestResponse.failure("请选择需要删除的用户");
        }
        for (SysUser u : users){
            if(u.getId() == 1){
                return RestResponse.failure("不能删除超级管理员");
            }else{
                sysUsersService.deleteUser(u);
            }
        }
        return RestResponse.success();
    }
    @ApiOperation(value = "/listByRoleId", httpMethod = "GET", notes = "根绝角色id查询用户")
    @GetMapping(value = "listByRoleId")
    @ResponseBody
    public String showUser(Integer roleId, int page, int limit) {
        JSONObject returnValue = new JSONObject();
        List<Integer> userids=sysUserRoleService.findByRoleId(roleId);
        QueryWrapper<SysUser> entityWrapper=new QueryWrapper<>();
        entityWrapper.in("id",userids);
        IPage<SysUser> users = sysUsersService.page(new Page<>(page,limit),entityWrapper);
        returnValue.put("users", users.getRecords());
        returnValue.put("totals", users.getTotal());
        return JSON.toJSONString(returnValue);
    }
}
